//
//  LMTimeTool.m
//  LiuMuKaMeng
//
//  Created by 江湖 on 2018/6/28.
//  Copyright © 2018年 六沐. All rights reserved.
//

#import "LMTimeTool.h"

@interface LMTimeTool()
@property (nonatomic ,assign) LMTimeType timeType;
@property(nonatomic,copy)NSString *starTime;
@property(nonatomic,copy)NSString *endTime;
@property(nonatomic,copy)NSString *sysTime;



@end
@implementation LMTimeTool
+ (LMTimeTool *)shareManage {
    //1.声明一个空的静态的单例对象
    static LMTimeTool *_single = nil;
    //2.声明一个静态的gcd的单次任务
    static dispatch_once_t onceTask;
    //3.执行gcd单次任务：对对象进行初始化
    dispatch_once(&onceTask, ^{
        _single = [[LMTimeTool alloc]init];
    });
    return _single;
}

//创建单例定时器
- (NSTimer *)shareTimeManageObj:(id)obj sel:(SEL)sel {
    //1.声明一个空的静态的单例对象
    static NSTimer *_singleTon = nil;
    //2.声明一个静态的gcd的单次任务
    static dispatch_once_t onceTask;
    //3.执行gcd单次任务：对对象进行初始化
    dispatch_once(&onceTask, ^{
        _singleTon = [NSTimer scheduledTimerWithTimeInterval:1 target:obj selector:sel userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_singleTon forMode:NSRunLoopCommonModes];
        [LMTimeTool shareManage].timer = _singleTon;
        [[LMTimeTool shareManage].timer setFireDate:[NSDate distantFuture]];
    });
    return _singleTon;
}

//创建单例定时器
- (dispatch_source_t )shareGcdTimeManage{
    static dispatch_source_t sourceT;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        sourceT = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(sourceT, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
        
        dispatch_source_set_event_handler(sourceT, ^{
          
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                });
        });
        dispatch_resume(sourceT);
        
    });
    return  sourceT;
}

- (void)cancelGcdTimer{
    dispatch_source_cancel([[LMTimeTool shareManage] shareGcdTimeManage]);
}
- (void)startGcdTimer{
//    dispatch_source_t sourceT = [[LMTimeTool shareManage] shareGcdTimeManage];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t sourceT = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(sourceT, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC,1* NSEC_PER_SEC);
    
    dispatch_source_set_event_handler(sourceT, ^{
      
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"----%@",[NSThread currentThread]);
            });
    });
    dispatch_resume(sourceT);
    
    
}
- (LMTimeTool *(^)(void))initGcdTime {
    return ^(void){
        [self shareGcdTimeManage];
        return self;
    };
}
- (LMTimeTool *(^)(id, SEL))initTime {
    return ^(id obj,SEL sel){
        [self shareTimeManageObj:obj sel:sel];
        return self;
    };
}

- (LMTimeTool *(^)(NSString *, NSString *, NSString *))timeParameter {
    return ^(NSString *starTime, NSString *endTime, NSString *sysTime){
        self.starTime = starTime;
        self.endTime  = endTime;
        self.sysTime  = sysTime;
        return self;
    };
}

- (LMTimeTool *(^)(SuccessfulBlock))success {
    return ^(SuccessfulBlock successBlock){
        self.successBlock = successBlock;
        [self getType];
        return self;
    };
}

- (LMTimeTool *(^)(CycleTimeBlock))cycle {
    return ^(CycleTimeBlock cycleBlock){
        self.cycleBlock = cycleBlock;
        [[LMTimeTool shareManage].timer setFireDate:[NSDate date]];
        return self;
    };
}

- (void)timers:(NSTimer*)timerr {
    self.timestamp--;
    [self getDetailTimeWithTimestamp:self.timestamp];
}

- (void)runTime {
        self.timestamp--;
        [self getDetailTimeWithTimestamp:self.timestamp];
}

- (LMTimeTool *(^)(LMTheTimeType))setTimeType
{
    return ^(LMTheTimeType type){
        [self setingTimeType:type];
        return self;
    };
}

- (void)setingTimeType:(LMTheTimeType)type {
    if ([LMTimeTool shareManage].timer) {
        if (type == LMTheTimeBegin) {
            //开始后刷新数据
            [self getType];
            [[LMTimeTool shareManage].timer setFireDate:[NSDate date]];
        } else if (type == LMTheTimePause){
            [[LMTimeTool shareManage].timer setFireDate:[NSDate distantFuture]];
        } else if (type == LMTheTimeStop){
            [[LMTimeTool shareManage].timer invalidate];
            [LMTimeTool shareManage].timer = nil;
        }
    }

}

- (void)getType {
    NSTimeInterval timestamp = [self timeValues:self.starTime time2:self.sysTime];
    self.timestamp = timestamp;
    if (self.timestamp <= 0 ) {
        //        已经开始
        NSTimeInterval timestamp1 = [self timeValues:self.endTime time2:self.sysTime];
        self.timestamp = timestamp1;
        if (timestamp1 <= 0) {
            //已结束
            self.timeType = LMTimeEnd;
            [[LMTimeTool shareManage].timer setFireDate:[NSDate distantFuture]];
          
        }else{
            self.timeType = LMTimeOngoing;
            //        活动进行中
            [[LMTimeTool shareManage].timer setFireDate:[NSDate date]];
        }
    }else{
        self.timeType = LMTimeNoStart;
        //        活动未开始
        [[LMTimeTool shareManage].timer setFireDate:[NSDate date]];
    }
    self.successBlock(self.timeType);
}

- (void)getDetailTimeWithTimestamp:(NSInteger)timestamp {
    NSInteger ms = timestamp;
    NSInteger ss = 1;
    NSInteger mi = ss * 60;
    NSInteger hh = mi * 60;
    NSInteger dd = hh * 24;
    
    // 剩余的
    NSInteger day = ms / dd;// 天
    NSInteger hour = (ms - day * dd) / hh;// 时
    NSInteger minute = (ms - day * dd - hour * hh) / mi;// 分
    NSInteger second = (ms - day * dd - hour * hh - minute * mi) / ss;// 秒
    //    NSLog(@"%zd日:%zd时:%zd分:%zd秒",day,hour,minute,second);
    NSString *leftTitle = @"距离开始";
    if (self.timeType == LMTimeOngoing) {
        leftTitle = @"本场剩余";
    }
    BOOL stop = NO;
    if (self.timestamp <= 0) {
        [[LMTimeTool shareManage].timer setFireDate:[NSDate distantFuture]];
        //获取下一期的数据
        stop = YES;
    }
    self.cycleBlock(self.timeType, stop,day,hour,minute,second);
}

//计算时间间隔
- (NSTimeInterval)timeValues:(NSString *)time1 time2:(NSString *)time2 {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    //然后创建日期对象
    //    2018-06-20 17:13:07
    NSDate *date1 = [dateFormatter dateFromString:time1];//
    NSDate *date2 = [dateFormatter dateFromString:time2];//
    
    //    NSDate *date = [NSDate date];
    
    //计算时间间隔（单位是秒）
    
    NSTimeInterval time = [date1 timeIntervalSinceDate:date2];
    return time;
}

@end
